from PyQt4.QtCore import QSettings
from deploy.constants import Config
import logging
import sys

# Add an "ALWAYS" level to logging for messages that should always be
# reported, but shouldn't imply a "severe" message to an observer.
logging.addLevelName(logging.CRITICAL + 10, 'ALWAYS')
logging.ALWAYS = logging._levelNames['ALWAYS']

class LoggingTee(object):
    '''Helper class to split logging streams to multiple locations.
    
    Taken from http://mail.python.org/pipermail/python-list/2000-August/049071.html
    '''
    def __init__(self, *fileobjects):
        self.fileobjects = fileobjects

    def write(self, string):
        for fileobject in self.fileobjects:
            fileobject.write(string)

    def flush(self):
        for fileobject in self.fileobjects:
            fileobject.flush()

logFile = None
logTee = None
configured = False

def setLoggingLevel():
    '''Set the global logging level from the stored value in settings.'''
    global logFile
    global logTee
    global configured

    settings = QSettings()
    stringLevel = str(settings.value(Config.DEBUG_LEVEL).toString())

    level = logging._levelNames.get(stringLevel, logging.INFO)

    if logFile is None:
        logFile = open('DeployThing.log', 'a')

    if logTee is None:
        logTee = LoggingTee(logFile, sys.stdout)

    # The first time through, we need to call logging.basicConfig to initialize logging
    if not configured:
        logging.basicConfig(stream = logTee, level = level)
        configured = True

    # Now we can change the level on the root logger
    rootLogger = logging.getLogger('')
    rootLogger.setLevel(level)

    # Log a message about the log level change that is always shown
    logger = logging.getLogger(__name__)
    logger.log(logging.ALWAYS, 'Root logging level changed to %s' % logging.getLevelName(rootLogger.getEffectiveLevel()))
